package com.yc.controller.manager.album;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.yc.controller.base.BaseController;
import com.yc.entity.Page;
import com.yc.entity.manager.AppAlbum;
import com.yc.util.AppUtil;
import com.yc.util.Const;
import com.yc.util.FileUpload;
import com.yc.util.ObjectExcelView;
import com.yc.util.PageData;
import com.yc.util.Jurisdiction;
import com.yc.util.Tools;
import com.yc.service.manager.album.AlbumManager;
import com.yc.service.manager.column.ColumnManager;
import com.yc.service.manager.product.ProductManager;

/** 
 * 说明：专辑管理
 * 创建人： 
 * 创建时间：2017-06-11
 */
@Controller
@RequestMapping(value="/album")
public class AlbumController extends BaseController {
	
	String menuUrl = "album/list.do"; //菜单地址(权限用)
	@Resource(name="albumService")
	private AlbumManager albumManager;
	@Resource(name="productService")
	private ProductManager productManager;
	@Resource(name="columnService")
	private ColumnManager columnService;
	
	/**保存
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/save")
	public ModelAndView save(HttpServletRequest request, MultipartFile bigpic,  MultipartFile minpic) throws Exception{
		logBefore(logger, Jurisdiction.getUsername()+"新增album");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		String name = request.getParameter("name");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(name)){
			pd.put("name", name.trim());
		}
		pd.put("status", status);
		//大图
	    if (bigpic != null) {
	    	String bigPicName = FileUpload.uploadImg(bigpic, request, Const.FILEPATHIMG + Const.MINIAPP_ALBUM_BIG);
	    	pd.put("bigpic", bigPicName);
		}
		//小图
	    if (minpic != null) {
	    	String minpicName = FileUpload.uploadImg(minpic, request, Const.FILEPATHIMG + Const.MINIAPP_ALBUM_MIN);
	    	pd.put("minpic", minpicName);
		}
	    pd.put("createTime", new Date());
		albumManager.save(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**删除
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	public void delete(PrintWriter out) throws Exception{
		logBefore(logger, Jurisdiction.getUsername()+"删除album");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return;} //校验权限
		PageData pd = new PageData();
		pd = this.getPageData();
		albumManager.delete(pd);
		out.write("success");
		out.close();
	}
	 /**批量删除
		 * @param
		 * @throws Exception
		 */
		@RequestMapping(value="/deleteAll")
		@ResponseBody
		public Object deleteAll() throws Exception{
			logBefore(logger, Jurisdiction.getUsername()+"批量删除album");
			if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return null;} //校验权限
			PageData pd = new PageData();		
			Map<String,Object> map = new HashMap<String,Object>();
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				albumManager.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
			return AppUtil.returnObject(pd, map);
		}
	
	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit(HttpServletRequest request, MultipartFile bigpic,  MultipartFile minpic) throws Exception{
		logBefore(logger, Jurisdiction.getUsername()+"修改album");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		String name = request.getParameter("name");
		String ID = request.getParameter("ID");
		String status = request.getParameter("status");
		String childapps = request.getParameter("childapps");
		if(StringUtils.isNotBlank(name)){
			pd.put("name", name.trim());
		}
		pd.put("status", status);
		pd.put("childapps", childapps);
		pd.put("id", ID);
		//大图
	    if (bigpic != null) {
	    	String bigPicName = FileUpload.uploadImg(bigpic, request, Const.FILEPATHIMG + Const.MINIAPP_ALBUM_BIG);
	    	pd.put("bigpic", bigPicName);
		}
		//小图
	    if (minpic != null) {
	    	String minpicName = FileUpload.uploadImg(minpic, request, Const.FILEPATHIMG + Const.MINIAPP_ALBUM_MIN);
	    	pd.put("minpic", minpicName);
		}
		albumManager.edit(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}

	/** 小程序列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/productlist")
	public ModelAndView productlist(Page page) throws Exception{
		logBefore(logger, Jurisdiction.getUsername()+"列表Product");
		//if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限(无权查看时页面会有提示,如果不注释掉这句代码就无法进入列表页面,所以根据情况是否加入本句代码)
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String keywords = pd.getString("PROD_NAME");				//关键词检索条件
		if(null != keywords && !"".equals(keywords)){
			pd.put("PROD_NAME", keywords.trim());
		}
		page.setPd(pd);
		List<PageData> varList = productManager.list(page);	
		List<PageData> newVarList = new ArrayList<PageData>();
		String childsapps = pd.getString("childapps");
		//如果当前专辑有下属小程序列表
		if(StringUtils.isNotBlank(childsapps)){
			//遍历小程序列表，确认小程序是否被当前专辑列表选中，被选中小程序界面复选框默认选中
			for(PageData eachPd : varList){
				Integer id = (Integer)eachPd.get("ID");
				if(StringUtils.isNotBlank(id.toString()) && (childsapps.indexOf("," + id) >= 0 || childsapps.indexOf(id + ",") >= 0)){
					eachPd.put("checked", "1");//小程序被选中
				}else{
					eachPd.put("checked", "0");//小程序没选中
				}
				newVarList.add(eachPd);
			}
			mv.addObject("varList", newVarList);
		}else{
			mv.addObject("varList", varList);
		}
		mv.setViewName("manager/album/product_list");
		List<PageData>	columnList = columnService.listAll(new PageData());	
		mv.addObject("columnList", columnList);
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	public ModelAndView list(Page page) throws Exception{
		logBefore(logger, Jurisdiction.getUsername()+"列表album");
		//if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限(无权查看时页面会有提示,如果不注释掉这句代码就无法进入列表页面,所以根据情况是否加入本句代码)
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String keywords = pd.getString("keywords");				//关键词检索条件
		if(null != keywords && !"".equals(keywords)){
			pd.put("keywords", keywords.trim());
		}
		page.setPd(pd);
		List<AppAlbum>	varList = albumManager.list(page);	//列出album列表
		mv.setViewName("manager/album/album_list");
		mv.addObject("varList", varList);
		mv.addObject("pd", pd);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	/**去新增页面
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		mv.setViewName("manager/album/album_edit");
		mv.addObject("msg", "save");
		mv.addObject("pd", pd);
		return mv;
	}	
	
	 /**去修改页面
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		AppAlbum album = albumManager.findById(pd);	//根据ID读取
		mv.setViewName("manager/album/album_edit");
		mv.addObject("msg", "edit");
		mv.addObject("album", album);
		return mv;
	}	
	
	/**
	 * 更改专辑下属小程序列表
	 * @return
	 */
	@RequestMapping("updatechildapps")
	public @ResponseBody Map<String, String> updatechildapps(HttpServletRequest request){
		Map<String, String> map = new HashMap<String, String>();
		String ids = request.getParameter("ids");
		String id = request.getParameter("id");
		PageData pd = new PageData();
		pd.put("childapps", ids);
		pd.put("id", id);
		try {
			albumManager.updatechildapps(pd);
			map.put("code", "1");
		} catch (Exception e) {
			logger.error("更改专辑下属小程序列表：",e);
			map.put("code", "0");
		}
		return map;
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
}
